package com.my.code.pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolUtil {
    /**
     * 核心线程数，会一直存活，即使没有任务，线程池也会维护线程的最少数量
     */
    private static final int SIZE_CORE_POOL = 5;
    /**
     * 线程池维护线程的最大数量
     */
    private static final int SIZE_MAX_POOL = 10;
    /**
     * 线程池维护线程所允许的空闲时间
     */
    private static final long ALIVE_TIME = 2000;//ms
    /**
     * 线程缓冲队列，超过这个数量的线程将会阻塞
     */
    private static BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(100);
    /**
     * 注意最后的参数是： RejectedExecutionHandler
     * Executors.newFixedThreadPool(n)对应的Handler 默认的是reject抛出异常
     * new ThreadPoolExecutor.CallerRunsPolicy() 表示的是没有shutdown之前，尝试将其执行完
     */
    private static ThreadPoolExecutor pool = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME, TimeUnit.MILLISECONDS, bqueue, new ThreadPoolExecutor.AbortPolicy());

    static {
        pool.prestartAllCoreThreads();//启动核心线程
    }

    public static ThreadPoolExecutor getPool() {
        return pool;
    }

}
